package service

import (
	"github.com/vueadmin/app/admin/internal/model"
	"github.com/vueadmin/app/admin/internal/svc"
	"github.com/vueadmin/utils/conv"
)

type baseconfigService struct{
	svcCtx *svc.ServiceContext
}

func NewBaseconfigService(svcCtx *svc.ServiceContext) *baseconfigService {
	return &baseconfigService{
		svcCtx: svcCtx,
	}
}

/**
 * @description(配置表单)
 * @buildcode(true)
*/
func (p baseconfigService) Index() (map[string]interface{}, error) {
	var entity []*model.Baseconfig
	if err := p.svcCtx.Db.Find(&entity).Error; err != nil {
		return nil,err
	}
	config := make(map[string]interface{})
	for _, val := range entity {
		config[val.Name] = val.Data
	}
	config["keyword"] = conv.StringToSlice(conv.String(config["keyword"]), ",")

	return config,nil
}

/**
 * @description(更新表单)
 * @buildcode(true)
*/
func (p baseconfigService) Update(req map[string]interface{}) error {
	column := make([]string, 0)
	var entity model.Baseconfig
	p.svcCtx.Db.Model(&entity).Pluck("name", &column)

	req["keyword"] = conv.SliceToString(req["keyword"].([]interface{}))

	for key, val := range req {
		if conv.IsValueInList(key, column) {
			if err := p.svcCtx.Db.Model(&entity).Where("name = ?", key).Update("data", val).Error; err != nil {
				return err
			}
		} else {
			if err := p.svcCtx.Db.Model(&entity).Create(map[string]interface{}{"name": key, "data": val}).Error; err != nil {
				return err
			}
		}
	}
	return nil
}

